﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

namespace SilverlightCalculator
{
    public class EntityBase : INotifyDataErrorInfo
    {
        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
        protected readonly Dictionary<string, List<string>> CurrentErrors;
       
        public EntityBase()
        {
            CurrentErrors = new Dictionary<string, List<string>>();            
        }       

        public IEnumerable GetErrors(string propertyName)
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                return (CurrentErrors.Values);
            }

            MakeOrCreatePropertyErrorList(propertyName);
            return CurrentErrors[propertyName];
        }

        public bool HasErrors
        {
            get
            {
                return (CurrentErrors.Where(c => c.Value.Count > 0).Count() > 0);
            }
        }        

        void FireErrorsChanged(string property)
        {
            if (ErrorsChanged != null)
            {
                ErrorsChanged(this, new DataErrorsChangedEventArgs(property));

            }
        }
        public void ClearErrorFromProperty(string property)
        {
            MakeOrCreatePropertyErrorList(property);
            CurrentErrors[property].Clear();
            FireErrorsChanged(property);
        }
        public void AddErrorForProperty(string property, string error)
        {
            MakeOrCreatePropertyErrorList(property);
            CurrentErrors[property].Add(error);
            FireErrorsChanged(property);
        }

        void MakeOrCreatePropertyErrorList(string propertyName)
        {
            if (!CurrentErrors.ContainsKey(propertyName))
            {
                CurrentErrors[propertyName] = new List<string>();
            }
        }        
    }
}
